package com.kbbywyclient.ui.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.kbbywyclient.R;
import com.kbbywyclient.app.API;
import com.kbbywyclient.app.Constants;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.CommissionWithdrawModule;
import com.kbbywyclient.presenter.CommissionWithdrawPresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.contarct.CommissionWithdrawContract;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.ImageLoaderUtils;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.widget.CustomDialog;
import com.kbbywyclient.widget.CustomToolBar;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Locale;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

/**
 * Created by Jiangzx on 2017/9/8 15:34.
 */

public class CommissionWithdrawActivity extends BaseActivity implements CommissionWithdrawContract.View{
    public static final double FEE=1;
    public static final String CARD_NUMBER_S="cardNumber";//银行卡号
    public static final String BANK_NAME_S="bankName";//银行名
    public static final String CARD_TYPE_I="cardType";//银行卡类型
    public static final String CARD_LOGO_S="cardLogo";//银行卡logo
    public static final String RULE_MINI_D="ruleMini";//提现规则最小值
    public static final String RULE_MAX_D="ruleMax";//提现规则最大值
    public static final String BALANCE_D="amount";//用户账户可提现余额
    @BindView(R.id.v_toolbar)
    CustomToolBar toolBar;
    @BindView(R.id.iv_card_logo)
    ImageView ivCardLogo;
    @BindView(R.id.tv_bank_card)
    TextView tvBankCard;//银行卡
    @BindView(R.id.et_amount)
    EditText etAmount;//提现金额
    @BindView(R.id.tv_available_amount)
    TextView tvAvailableAmount;//当前可提现余额

    @BindView(R.id.bt_withdraw)
    Button btWithdraw;

    @Inject
    CommissionWithdrawPresenter presenter;

    double min;
    double max;
    double balance;
    int cardType;
    String cardName;
    String cardNumber;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_commission_withdraw;
    }

    @Override
    protected void initView() {
        toolBar.setLeftViewOnClickLinster(v->finish());
        toolBar.setRightViewOnClickLinster(v->
            ActivitySkipUtil.skipAnotherActivity(CommissionWithdrawActivity.this,
                    WithdrawMoneyRecordActivity.class));
        //输入框最多保留2位小数
        etAmount.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL|InputType.TYPE_CLASS_NUMBER);
        etAmount.setFilters(new InputFilter[]{(source, start, end, dest, dstart, dend) -> {
            if(source.equals(".") && dest.toString().length() == 0){
                return "0.";
            }
            if(dest.toString().contains(".")){
                int index = dest.toString().indexOf(".");
                int length = dest.toString().substring(index).length();
                if(length == 3){
                    return "";
                }
            }
            return null;
        }});
    }

    @Override
    public void initData() {
        Intent intent=getIntent();
        ImageLoaderUtils.displayImage(ivCardLogo, API.PIC_ADDRESS+intent.getStringExtra(CARD_LOGO_S));
        cardName=intent.getStringExtra(BANK_NAME_S);
        cardNumber=intent.getStringExtra(CARD_NUMBER_S);
        cardType=intent.getIntExtra(CARD_TYPE_I,1);
        String cardInfo=cardName+
                (cardType==1?"储蓄卡":"信用卡")+
                " ("+cardNumber+")";
        tvBankCard.setText(cardInfo);

        min=intent.getDoubleExtra(RULE_MINI_D,0.00);
        max=intent.getDoubleExtra(RULE_MAX_D,Double.MAX_VALUE);
        balance=intent.getDoubleExtra(BALANCE_D,0.00);

        SpannableString balanceStr=
                new SpannableString("当前可提现余额："+
                        (String.format(Locale.CHINESE,Constants.AMOUNT_FORMAT,balance))+
                        "元");
        balanceStr.setSpan(new ForegroundColorSpan(0XFFFF7B60),
                8,balanceStr.length(),
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tvAvailableAmount.setText(balanceStr);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("佣金提现");
    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getCommissionWithdrawComponent(new CommissionWithdrawModule(this)).inject(this);
    }

    @OnTextChanged(R.id.et_amount)
    public void afterTextChange(Editable s){
        String text=s.toString().trim();
        if(text.length()>0){
            try{
                double amount=Double.parseDouble(text);
                if(amount>0){
                    btWithdraw.setEnabled(true);
                }else{
                    btWithdraw.setEnabled(false);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            btWithdraw.setEnabled(false);
        }
    }

    CustomDialog ensureDialog;

    @OnClick(R.id.bt_withdraw)
    public void onClick(View view){
        switch (view.getId()){
            case R.id.bt_withdraw:
                try{
                    BigDecimal balanceDecimal=new BigDecimal(balance);
                    if(balanceDecimal.doubleValue()==0){
                        ToastUtil.showLong("您当前可提余额为0.00元，不可提现");
                        return;
                    }
                    BigDecimal input=new BigDecimal(etAmount.getText().toString().trim());
                    if(input.doubleValue()>balanceDecimal.doubleValue()){
                        ToastUtil.showLong("输入金额超过可提余额，请重新输入");
                        return;
                    }
                    if(input.doubleValue()<1){
                        ToastUtil.showLong("单笔提现不能低于1.00元，请重新输入");
                        return;
                    }
                    if(input.doubleValue()>max){
                        ToastUtil.showLong("超过单笔提现最高限额"+
                                (String.format(Locale.CHINESE, Constants.AMOUNT_FORMAT,max))+
                                "元，请重新输入");
                        return;
                    }
                    if(input.doubleValue()<min){
                        ToastUtil.showLong("单笔提现不能低于"+
                                (String.format(Locale.CHINESE, Constants.AMOUNT_FORMAT,min))+
                                "元，请重新输入");
                        return;
                    }
                    if(balanceDecimal.subtract(input).doubleValue()<FEE){
                        final double available=
                                balanceDecimal.subtract(new BigDecimal(FEE)).doubleValue();
                        ensureDialog=new CustomDialog(this, R.style.Customdialog, "卡贝贝提示",
                                "此次提现金额为￥"+
                                        (String.format(Locale.CHINESE,Constants.AMOUNT_FORMAT,input.doubleValue()))+
                                                "，"+
                                        "手续费为￥"+
                                        (String.format(Locale.CHINESE,Constants.AMOUNT_FORMAT,FEE))+
                                        "，"+
                                        "实际到账金额为￥"+
                                        (String.format(Locale.CHINESE,Constants.AMOUNT_FORMAT,available)),
                                new CustomDialog.ButtonListener() {
                            @Override
                            public void left() {
                                ensureDialog.dismiss();
                            }

                            @Override
                            public void right() {
                                ensureDialog.dismiss();
                                presenter.withdraw(getUser(CommissionWithdrawActivity.this).getSalesID(),
                                        balanceDecimal.doubleValue());
                            }
                        },"取消","全部提现");
                        ensureDialog.show();
                        return;
                    }else{
                        final double available=
                                input.subtract(new BigDecimal(FEE)).doubleValue();
                        ensureDialog=new CustomDialog(this, R.style.Customdialog, "卡贝贝提示",
                                "此次提现金额为￥"+
                                        (String.format(Locale.CHINESE,Constants.AMOUNT_FORMAT,input.doubleValue()))+
                                        "，"+
                                        "手续费为￥"+
                                        (String.format(Locale.CHINESE,Constants.AMOUNT_FORMAT,FEE))+
                                        "，"+
                                        "实际到账金额为￥"+
                                        (String.format(Locale.CHINESE,Constants.AMOUNT_FORMAT,available)),
                                new CustomDialog.ButtonListener() {
                            @Override
                            public void left() {
                                ensureDialog.dismiss();
                            }

                            @Override
                            public void right() {
                                ensureDialog.dismiss();
                                presenter.withdraw(getUser(CommissionWithdrawActivity.this).getSalesID(),
                                        input.doubleValue());
                            }
                        },"取消","提现");
                        ensureDialog.show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
        }
    }

    @OnClick(R.id.iv_card_manage)
    public void onCardManageClick(View view){
        ActivitySkipUtil.skipAnotherActivity(CommissionWithdrawActivity.this,
                BankCardManageActivity.class);
    }

    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    @Override
    public void onSubmitSuccess(double amount) {
        HashMap<String,Object> params=new HashMap<>();
        params.put(CommissionWithdrawSubmitActivity.CARD_INFO_S,
                cardName+" 尾号"+cardNumber);
        params.put(CommissionWithdrawSubmitActivity.AMOUNT_D, amount);
        ActivitySkipUtil.skipAnotherActivity(CommissionWithdrawActivity.this,
                CommissionWithdrawSubmitActivity.class,
                params);
        finish();
    }
}
